<template>
	<!-- 分享对话框 -->
	<el-drawer
		:title="title"
		:visible.sync="visibleInChild"
		:close-on-click-modal="false"
		size="100%"
		@close="handleDialogCancel"
	>
		<el-form
			:model="article"
			ref="newBlogForm"
			label-suffix="："
			label-width="100px"
			:label-position="screenWidth <= 520 ? 'top' : 'right'"
			:rules="rules"
		>
			<el-form-item label="title" prop="articleTitle">
				<el-input
					maxlength="300"
					v-model="article.articleTitle"
					placeholder="please input blog title"
				></el-input>
			</el-form-item>
			<el-form-item label="video url" prop="videoUrl">
				<el-input
					maxlength="2000"
					v-model="article.videoUrl"
					placeholder="please input video url"
				></el-input>
			</el-form-item>
			<el-form-item label="content" prop="articleContent">
				<mavon-editor
					ref="md"
					@imgAdd="imgAdd"
					@imgDel="imgDel"
					v-model="article.articleContent"
					:language="$i18n.locale == 'en_US' ? 'en' : 'zh-CN'"
				/>
			</el-form-item>

			<el-form-item>
				<el-button
					size="small"
					type="success"
					:loading="sureBtnLoading"
					@click="handleDialogSure('newBlogForm')"
					>submit</el-button
				>

				<el-button type="danger" size="small" @click="resetForm('newBlogForm')"
					>reset all</el-button
				>
				<el-button @click="handleDialogCancel" size="small">{{
					$t('components_header_321')
				}}</el-button>
			</el-form-item>
		</el-form>
	</el-drawer>
</template>

<script>
import store from '@/store/index.js'
import metaidv2Utils from '@/utils/metaidv2Utils.js'

export default {
	name: 'newBlogDialog',
	components: {},
	props: {
		visible: {
			required: false,
			default: false,
			type: Boolean
		}
	},

	data() {
		return {
			// 对话框数据
			article: {
				articleTitle: '',
				articleContent: '',
				videoUrl: '',
				imageList: {}
			},
			rules: {
				articleTitle: [
					{
						required: false,
						message: 'blog title can not empty',
						trigger: 'blur'
					}
				],
				articleContent: [
					{
						required: true,
						message: 'blog content can not empty',
						trigger: 'blur'
					}
				]
			},
			sureBtnLoading: false
		}
	},
	created() {},
	computed: {
		title() {
			return 'New Blog'
		},
		// 屏幕宽度
		screenWidth() {
			return store.state.common.screenWidth
		},
		finallyContent() {
			//return `#MetaDiskBuzz<br/>${this.form.content}`
			return `${this.article.articleContent}`
		},
		visibleInChild: {
			get() {
				return this.visible
			},
			set(val) {
				this.$emit('update:visible', val)
			}
		}
	},
	methods: {
		async imgDel(delFileInfo) {
			console.log(this.article)
			console.log('imgDel', delFileInfo)
			const posImage = this.article.imageList[delFileInfo[0]]
			console.log('posImage:', posImage)
			posImage.del = true
			this.article.imageList[delFileInfo[0]] = posImage
			console.log(this.article)
			delete this.article.imageList[delFileInfo[0]]
			console.log(this.article)
		},
		async imgAdd(pos, file) {
			//console.log('imgAdd', pos, file)
			const imageInfo = {
				file,
				pos,
				key: `![${file.name}](${pos})`,
				transactions: []
			}
			//console.log('imageInfo:', imageInfo)

			// 压缩图片
			const compressed = await metaidv2Utils.compressImage(file)
			const fileResult = await metaidv2Utils.fileToAttachment(
				file.type === 'image/gif' ? file : compressed
			)
			//console.log('fileResult', fileResult)

			const opReturnFieldList = [
				Buffer.from('metaid'),
				Buffer.from('create'),
				Buffer.from('/file'),
				Buffer.from('0'),
				Buffer.from('1.0.0'),
				Buffer.from(`${fileResult.fileType};binary`),
				Buffer.from(Buffer.from(fileResult.data, 'hex'))
			]
			//console.log('imageTxs', opReturnFieldList.toString())
			const { transactions } = await window.$walletUtils.createPin(
				opReturnFieldList,
				{
					serialAction: 'combo'
				}
			)
			if (!transactions) {
				throw new Error('upload image file failed')
			}

			imageInfo.metafile =
				'metafile://' +
				transactions[transactions.length - 1].txComposer.getTxId() +
				'i0'
			imageInfo.transactions = transactions

			//console.log('imageInfo-finally:', imageInfo)
			this.article.imageList[pos] = imageInfo
			//console.log('article-finally:', this.article)
		},
		addArticleCover(res) {
			this.article.articleCover = res
		},
		handleDialogCancel() {
			this.visibleInChild = false
		},
		resetForm(formName) {
			this.$refs[formName].resetFields()
		},
		async handleDialogSure(formName) {
			this.sureBtnLoading = true
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					//console.log('finallyContent', this.finallyContent)
					const backupArticleCotent = this.article.articleContent
					const transactions = []
					for (const pos in this.article.imageList) {
						const posImage = this.article.imageList[pos]
						//console.log('posImage', posImage)
						transactions.push(posImage.transactions[0])
						//console.log('transactions', transactions)
						this.$refs.md.$img2Url(posImage.pos, posImage.metafile)
					}

					const options = {
						title: this.article.articleTitle,
						content: this.article.articleContent,
						videoUrl: this.article.videoUrl,
						transactions: transactions
					}
					//console.log('options', options)
					const res = await window.$walletUtils
						.simpleblog(options)
						.catch((res) => {
							this.article.articleContent = backupArticleCotent
							this.sureBtnLoading = false
							this.$message.error('Error new blog:' + res?.message)
						})
					console.log('res', res)
					this.sureBtnLoading = false
					if (res == '__txcanceled__') {
						this.article.articleContent = backupArticleCotent
						return
					}

					if (res) {
						this.$message.success(this.$t('csp_026'))
						this.article.articleContent = backupArticleCotent
						//this.$refs[formName].resetFields()
						setTimeout(() => {
							this.$emit('newBlogSuccess')
						}, 500)
						this.visibleInChild = false
					}
				} else {
					this.sureBtnLoading = false
				}
			})
		}
	}
}
</script>

<style lang="stylus" scoped>
@import '~_a/styles/varibles.styl';
.myCenter{
  padding-left: 20px;
}
.success-tip {
  margin-bottom: 16px;
  text-align: center;
  color: $Success;

  .el-icon-success {
    margin-right: 8px;
    height: 20px;
    line-height: 20px;
  }


}
</style>
